package org.jeecg.modules.clue.factory.carPlate;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.clue.entity.ClueRecordTask;
import org.jeecg.modules.clue.entity.ClueTaskQueryLog;
import org.jeecg.modules.clue.enums.ClueQueryStatus;
import org.jeecg.modules.clue.enums.TaskPushStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

/**
 * 汽车之家平台
 */
@Component("QCZJCarPlate")
@Slf4j
public class QCZJCarPlateService implements CarPlateService {

    private static String PUSH_URL = "https://openapi.autohome.com.cn/che168/apiclueopen/CarEstimate/AddOpenClueByConfig.ashx";
    private static String QUERY_URL = "https://openapi.autohome.com.cn/che168/apiclueopen/CarEstimate/ConeBalance.ashx";


    @Override
    public void push(ClueRecordTask recordTask) {
        log.info("QCZJCarPlate 开始推送={}", JSON.toJSON(recordTask));
        String appId = recordTask.getTpUsername();
        String accessToken = recordTask.getTpSecretKey();
        String mobile = recordTask.getPhone();
        String city = recordTask.getCity();

        String brandName = recordTask.getBrandName();
        String seriesName = recordTask.getSeriesName();
        String specName = recordTask.getSpecName();
        Date firstRegTime = recordTask.getFirstRegTime();


        String requestUrl = String.format("%s?access_token=%s", PUSH_URL, accessToken);
        HttpRequest request = HttpUtil.createPost(requestUrl);
        request.contentType("application/json");
        JSONObject bodyMap = new JSONObject();
        bodyMap.put("appId", appId);
        bodyMap.put("mobile", mobile);
        bodyMap.put("cityname", city);
        bodyMap.put("brandname", Optional.ofNullable(brandName).orElse(""));
        bodyMap.put("seriesname", Optional.ofNullable(seriesName).orElse(""));
        bodyMap.put("specname", Optional.ofNullable(specName).orElse(""));
        if (null != firstRegTime) {
            bodyMap.put("firstRegTime", DateUtil.format(firstRegTime, "yyyy/MM/dd"));
        }


        request.body(bodyMap.toJSONString());
        log.info("requestUrl {}", requestUrl);
        log.info("requestBody {}", bodyMap);
        HttpResponse execute = request.execute();
        String body = execute.body();
        log.info("QCZJCarPlate 推送结果={}", body);

        JSONObject resultBody = JSONObject.parseObject(body);
        recordTask.setRemark(resultBody.toJSONString());
        if (StringUtils.isNotBlank(resultBody.getString("returncode")) && "0".equals(resultBody.getString("returncode"))) {
            recordTask.setPushStatus(TaskPushStatus.推送成功.status);
            String cclid = resultBody.getString("cclid");
            recordTask.setTpCId(cclid);
        } else {
            recordTask.setPushStatus(TaskPushStatus.推送失败.status);
        }
        recordTask.setPushTime(new Date());
    }



    @Override
    public void query(ClueTaskQueryLog queryLog) {
        log.info("QCZJCarPlate 开始查询={}", JSON.toJSON(queryLog));
        String cId = queryLog.getTpCId();
        String appId = queryLog.getTpUsername();
        String accessToken = queryLog.getTpSecretKey();

        String requestUrl = String.format("%s?access_token=%s&cclid=%s&appid=%s", QUERY_URL, accessToken, cId, appId);
        HttpRequest request = HttpUtil.createGet(requestUrl);
//        request.contentType("application/json");
        log.info("requestUrl {}", requestUrl);

        HttpResponse execute = request.execute();
        String body = execute.body();
        log.info("QCZJCarPlate 查询结果={}", body);

        JSONObject resultBody = JSONObject.parseObject(body);
        if (null == resultBody.getInteger("returncode") || 0 != resultBody.getInteger("returncode")) {
            queryLog.setRemark(resultBody.toJSONString());
            queryLog.setQueryStatus(ClueQueryStatus.查询失败.status);
        } else {
            JSONObject result = resultBody.getJSONObject("result");
            queryLog.setQczjDistributeStatus(Optional.ofNullable(result.getString("distributeStatus")).orElse(""));
            queryLog.setQczjAppealStatus(Optional.ofNullable(result.getString("appealStatus")).orElse(""));
            queryLog.setQczjFilterateStatus(Optional.ofNullable(result.getString("filterateStatus")).orElse(""));
            queryLog.setQczjCheckStatus(Optional.ofNullable(result.getString("checkStatus")).orElse(""));

        }

    }
}
